package com.huabo.contract.service.impl;


import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import com.huabo.contract.config.DateBaseConfig;
import com.huabo.contract.oracle.entity.TblFlow;
import com.huabo.contract.oracle.mapper.TblFlowMapper;
import com.huabo.contract.oracle.mapper.TblOrganizationMapper;
import com.huabo.contract.util.DateUtils;
import org.springframework.stereotype.Service;

import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.DateUtil;
import com.hbfk.util.PageInfo;
import com.huabo.contract.oracle.entity.TblContractTypeof;
import com.huabo.contract.oracle.mapper.TblContractTypeofMapper;
import com.huabo.contract.oracle.mapper.TblCyhwUnitMapper;
import com.huabo.contract.service.TblContractTypeofService;
import com.huabo.contract.util.Tree;

@Service
public class TblContractTypeofServiceImpl implements TblContractTypeofService {
	@Resource
	private TblContractTypeofMapper tblContractTypeofMapper;

	@Resource
	private TblFlowMapper tblFlowMapper;

	@Resource
	private TblOrganizationMapper tblOrganizationMapper;
	
	@Resource
	private TblCyhwUnitMapper tblCyhwUnitMapper;
	
    @Override
    public Map<String, Object> findAllListToCreateContract(String token, String staffId) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			try {
				TblStaffUtil staff = DealUserToken.parseUserToken(token);
				if (staff == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				List<TblContractTypeof> typeofList = tblContractTypeofMapper.selectAllList(staff.getCurrentOrg().getOrgid());
				for (TblContractTypeof of : typeofList) {
					List<TblContractTypeof> list = tblContractTypeofMapper.selectListByParent(of.getTypeid());
					of.setChildrenList(list);
				}
				resultMap.put("code", "1");
				resultMap.put("msg", "访问接口成功");
				resultMap.put("typeofList", typeofList);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return resultMap;
		} else {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			try {
				TblStaffUtil staff = DealUserToken.parseUserToken(token);
				if (staff == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				List<TblContractTypeof> typeofList = tblContractTypeofMapper.selectAllList(staff.getCurrentOrg().getOrgid());
				for (TblContractTypeof of : typeofList) {
					List<TblContractTypeof> list = tblContractTypeofMapper.selectListByParent(of.getTypeid());
					of.setChildrenList(list);
				}
				resultMap.put("code", "1");
				resultMap.put("msg", "访问接口成功");
				resultMap.put("typeofList", typeofList);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return resultMap;
		}
    }

    @Override
    public Map<String, Object> findPageInfoList(Integer pageNumber, Integer pageSize,String typeId, String choiceTypeName, String token, String staffId) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			try {
				TblStaffUtil staff = DealUserToken.parseUserToken(token);
				if (staff == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				PageInfo<TblContractTypeof> pageInfo = new PageInfo<TblContractTypeof>();
				TblContractTypeof condition = new TblContractTypeof();
				condition.setOrgid(new BigDecimal(staff.getCurrentOrg().getOrgid().intValue()));
				if (choiceTypeName != null && !"".equals(choiceTypeName)) {
					condition.setTypename(choiceTypeName);
				}
				if (typeId != null) {
					condition.setTypeid(new BigDecimal(typeId));
				}
				pageInfo.setCurrentPage(pageNumber);
				pageInfo.setCondition(condition);
				pageInfo.setPageSize(pageSize);
				pageInfo.setTlist(tblContractTypeofMapper.selectLedgerListPageInfo(pageInfo));
				pageInfo.setTotalRecord(tblContractTypeofMapper.selectLedgerCountPageIfo(pageInfo));
				resultMap.put("code", "1");
				resultMap.put("msg", "访问接口成功");
				resultMap.put("data", pageInfo);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return resultMap;
		} else {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			try {
				TblStaffUtil staff = DealUserToken.parseUserToken(token);
				if (staff == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				PageInfo<TblContractTypeof> pageInfo = new PageInfo<TblContractTypeof>();
				TblContractTypeof condition = new TblContractTypeof();
				condition.setOrgid(new BigDecimal(staff.getCurrentOrg().getOrgid().intValue()));
				if (choiceTypeName != null && !"".equals(choiceTypeName)) {
					condition.setTypename(choiceTypeName);
				}
				if (typeId != null) {
					condition.setTypeid(new BigDecimal(typeId));
				}
				pageInfo.setCurrentPage(pageNumber);
				pageInfo.setCondition(condition);
				pageInfo.setPageSize(pageSize);
				pageInfo.setTlist(tblContractTypeofMapper.selectLedgerListPageInfo(pageInfo));
				pageInfo.setTotalRecord(tblContractTypeofMapper.selectLedgerCountPageIfo(pageInfo));
				resultMap.put("code", "1");
				resultMap.put("msg", "访问接口成功");
				resultMap.put("data", pageInfo);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return resultMap;
		}
    }

    @Override
    public List<Tree> getFatherTree(BigDecimal orgid) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			List<Tree> trees = new ArrayList<Tree>();
			List<Tree> ctrees = new ArrayList<Tree>();
			Tree tree = null;
			List<TblContractTypeof> list = this.tblContractTypeofMapper.selectAllList(orgid);
			for (TblContractTypeof type : list) {
				tree = new Tree();
				tree.setName(type.getTypename());
				tree.setId(type.getTypeid());
				tree.setpId(new BigDecimal(0));
				tree.setOpen(false);
				tree.setIsParent(false);
				ctrees.add(tree);
			}
			Tree ftree = new Tree();
			ftree.setName("全部");
			ftree.setId(new BigDecimal(0));
			ftree.setpId(null);
			ftree.setOpen(true);
			ftree.setIsParent(true);
			ftree.setChildren(ctrees);
			trees.add(ftree);
			return trees;
		} else {
			List<Tree> trees = new ArrayList<Tree>();
			List<Tree> ctrees = new ArrayList<Tree>();
			Tree tree = null;
			List<TblContractTypeof> list = this.tblContractTypeofMapper.selectAllList(orgid);
			for (TblContractTypeof type : list) {
				tree = new Tree();
				tree.setName(type.getTypename());
				tree.setId(type.getTypeid());
				tree.setpId(new BigDecimal(0));
				tree.setOpen(false);
				tree.setIsParent(false);
				ctrees.add(tree);
			}
			Tree ftree = new Tree();
			ftree.setName("全部");
			ftree.setId(new BigDecimal(0));
			ftree.setpId(null);
			ftree.setOpen(true);
			ftree.setIsParent(true);
			ftree.setChildren(ctrees);
			trees.add(ftree);
			return trees;
		}
    }

    @Override
    public Map<String, Object> saveContractType(String[] typeNameArr, Integer parentid, String token, String staffId) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			try {
				TblStaffUtil user = DealUserToken.parseUserToken(token);
				if (user == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				List<TblContractTypeof> typeList = new ArrayList<TblContractTypeof>(0);
				TblContractTypeof type = null;
				String typeNameStr = "";
				StringBuffer nameSb = new StringBuffer();
				if (parentid == null) {
					for (int i = 0; i < typeNameArr.length; i++) {
						type = new TblContractTypeof();
						type.setCreatestaff(user.getStaffid());
						type.setCreatetime(new Date());
						type.setOrgid(new BigDecimal(user.getCurrentOrg().getOrgid().intValue()));
						type.setTypename(typeNameArr[i]);
						typeList.add(type);
						nameSb.append("'" + typeNameArr[i] + "',");
					}
				} else {
					for (int i = 0; i < typeNameArr.length; i++) {
						type = new TblContractTypeof();
						type.setCreatestaff(user.getStaffid());
						type.setCreatetime(new Date());
						type.setOrgid(new BigDecimal(user.getCurrentOrg().getOrgid().intValue()));
						type.setTypename(typeNameArr[i]);
						type.setPageurl("default");
						type.setSettingid(TblContractTypeof.delfaultSetting);
						type.setParentid(new BigDecimal(parentid));
						typeList.add(type);
						nameSb.append("'" + typeNameArr[i] + "',");
					}
				}

				nameSb.deleteCharAt(nameSb.length() - 1);
				typeNameStr = nameSb.toString();
				List<TblContractTypeof> retypeList = this.tblContractTypeofMapper.selectRepeatTypeName(user.getCurrentOrg().getOrgid(), typeNameStr);
				if (retypeList != null && retypeList.size() > 0) {
					resultMap.put("code", "0");
					resultMap.put("msg", "合同类型重复！");
					return resultMap;
				}
				for (TblContractTypeof typeof : typeList) {
					this.tblContractTypeofMapper.saveContractTypeof(typeof);
				}
				resultMap.put("code", "1");
				resultMap.put("msg", "访问接口成功");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return resultMap;
		} else {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			try {
				TblStaffUtil user = DealUserToken.parseUserToken(token);
				if (user == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				List<TblContractTypeof> typeList = new ArrayList<TblContractTypeof>(0);
				TblContractTypeof type = null;
				String typeNameStr = "";
				StringBuffer nameSb = new StringBuffer();
				if (parentid == null) {
					for (int i = 0; i < typeNameArr.length; i++) {
						type = new TblContractTypeof();
						type.setCreatestaff(user.getStaffid());
						type.setCreatetime(new Date());
						type.setOrgid(new BigDecimal(user.getCurrentOrg().getOrgid().intValue()));
						type.setTypename(typeNameArr[i]);
						typeList.add(type);
						nameSb.append("'" + typeNameArr[i] + "',");
					}
				} else {
					for (int i = 0; i < typeNameArr.length; i++) {
						type = new TblContractTypeof();
						type.setCreatestaff(user.getStaffid());
						type.setCreatetime(new Date());
						type.setOrgid(new BigDecimal(user.getCurrentOrg().getOrgid().intValue()));
						type.setTypename(typeNameArr[i]);
						type.setPageurl("default");
						type.setSettingid(TblContractTypeof.delfaultSetting);
						type.setParentid(new BigDecimal(parentid));
						typeList.add(type);
						nameSb.append("'" + typeNameArr[i] + "',");
					}
				}

				nameSb.deleteCharAt(nameSb.length() - 1);
				typeNameStr = nameSb.toString();
				List<TblContractTypeof> retypeList = this.tblContractTypeofMapper.selectRepeatTypeName(user.getCurrentOrg().getOrgid(), typeNameStr);
				if (retypeList != null && retypeList.size() > 0) {
					resultMap.put("code", "0");
					resultMap.put("msg", "合同类型重复！");
					return resultMap;
				}
				for (TblContractTypeof typeof : typeList) {
					this.tblContractTypeofMapper.saveContractTypeof(typeof);
				}
				resultMap.put("code", "1");
				resultMap.put("msg", "访问接口成功");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return resultMap;
		}
    }

    @Override
    public Map<String, Object> modifyContractType(String token, String staffId, String typeId, String typeName) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			try {
				TblStaffUtil user = DealUserToken.parseUserToken(token);
				if (user == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				Integer count = this.tblContractTypeofMapper.selectContractCountByContractType(user.getCurrentOrg().getOrgid(), typeId);
				if (count > 0) {
					resultMap.put("code", "-2");
					resultMap.put("msg", "已被使用无法删除！");
					return resultMap;
				}
				Integer reCount = this.tblContractTypeofMapper.selectRepeatCount(typeName, user.getCurrentOrg().getOrgid(), typeId);
				if (reCount > 0) {
					resultMap.put("code", "-1");
					resultMap.put("msg", "合同类型重复！");
					return resultMap;
				}

				TblContractTypeof type = this.tblContractTypeofMapper.selectEntityById(typeId);
				type.setTypename(typeName);
				type.setUpdatestaff(user.getStaffid());
				type.setUpdatetime(new Date());
				this.tblContractTypeofMapper.updateContractTypeof(type);
				resultMap.put("code", "1");
				resultMap.put("msg", "更新成功！");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return resultMap;
		} else {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			try {
				TblStaffUtil user = DealUserToken.parseUserToken(token);
				if (user == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				Integer count = this.tblContractTypeofMapper.selectContractCountByContractType(user.getCurrentOrg().getOrgid(), typeId);
				if (count > 0) {
					resultMap.put("code", "-2");
					resultMap.put("msg", "已被使用无法删除！");
					return resultMap;
				}
				Integer reCount = this.tblContractTypeofMapper.selectRepeatCount(typeName, user.getCurrentOrg().getOrgid(), typeId);
				if (reCount > 0) {
					resultMap.put("code", "-1");
					resultMap.put("msg", "合同类型重复！");
					return resultMap;
				}

				TblContractTypeof type = this.tblContractTypeofMapper.selectEntityById(typeId);
				type.setTypename(typeName);
				type.setUpdatestaff(user.getStaffid());
				type.setUpdatetime(new Date());
				this.tblContractTypeofMapper.updateContractTypeof(type);
				resultMap.put("code", "1");
				resultMap.put("msg", "更新成功！");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return resultMap;
		}
    }

    @Override
    public Map<String, Object> removeContractType(String typeId, String token, String staffId) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			try {
				TblStaffUtil user = DealUserToken.parseUserToken(token);
				if (user == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				Integer count = this.tblContractTypeofMapper.selectContractCountByType(user.getCurrentOrg().getOrgid(), typeId);

				if (count > 0) {
					resultMap.put("code", "-1");
					resultMap.put("msg", "已被使用无法删除！");
					return resultMap;
				}
				this.tblContractTypeofMapper.deleteContractTypeByParentId(typeId);
				this.tblContractTypeofMapper.deleteContractTypeByTypeId(typeId);
				resultMap.put("code", "0");
				resultMap.put("msg", "删除成功！");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return resultMap;
		} else {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			try {
				TblStaffUtil user = DealUserToken.parseUserToken(token);
				if (user == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				Integer count = this.tblContractTypeofMapper.selectContractCountByType(user.getCurrentOrg().getOrgid(), typeId);

				if (count > 0) {
					resultMap.put("code", "-1");
					resultMap.put("msg", "已被使用无法删除！");
					return resultMap;
				}
				this.tblContractTypeofMapper.deleteContractTypeByParentId(typeId);
				this.tblContractTypeofMapper.deleteContractTypeByTypeId(typeId);
				resultMap.put("code", "0");
				resultMap.put("msg", "删除成功！");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return resultMap;
		}
    }

	@Override
	public Map<String, Object> toAddContract(BigDecimal flowId, Integer typeId, String token) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			Map<String, Object> dataMap = new HashMap<String, Object>(0);
			try {
				TblStaffUtil user = DealUserToken.parseUserToken(token);
				if (user == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				SimpleDateFormat sdFormat = new SimpleDateFormat("yyyyMMSSS");
				SimpleDateFormat nyr = new SimpleDateFormat("yyyy-MM-dd");
				Calendar cal = Calendar.getInstance();
				java.util.Date date = cal.getTime();
				String createTime = nyr.format(date);
				TblFlow flow = null;
				if (flowId != null && flowId.toString().trim().length() > 0) {
					flow = this.tblFlowMapper.findFlowInfoById(flowId.toString());
				}

				if ("HTGL005".equals(flow.getFlownumber()) || "HTGL002".equals(flow.getFlownumber()) || "HTGL007".equals(flow.getFlownumber())) {
					String writen = this.tblOrganizationMapper.selectWrittenDeptByOrgId(user.getLinkOrg().getOrgid());
					String writenDept = this.tblOrganizationMapper.selectWrittenDeptByOrgId(user.getLinkDetp().getOrgid());
					String year = DateUtil.parseDate(new Date(), "yyyy");
					String contractno = null;
					if("HTGL007".equals(flow.getFlownumber())) {
						contractno = writen+"合同范本["+year+"]";
					}else {
						contractno = writen+writenDept+"["+year+"]";
					}
					
					String no = this.tblCyhwUnitMapper.selectCountByContractNo(contractno,contractno+"%",flow.getFlownumber());
					if(no != null) {
						 no = no.replace(contractno, "");
					}else {
						no = "0";
					}
		            contractno += (Integer.parseInt(no)+1);
					dataMap.put("contractno", contractno+"号");
				}
				dataMap.put("flowname", flow.getFlowname());
				dataMap.put("flowid", flowId);
				dataMap.put("createDate", createTime);
				resultMap.put("code", "1");
				resultMap.put("msg", "访问接口成功");
				resultMap.put("data", dataMap);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return resultMap;
		} else {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			Map<String, Object> dataMap = new HashMap<String, Object>(0);
			try {
				TblStaffUtil user = DealUserToken.parseUserToken(token);
				if (user == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				SimpleDateFormat sdFormat = new SimpleDateFormat("yyyyMMSSS");
				SimpleDateFormat nyr = new SimpleDateFormat("yyyy-MM-dd");
				Calendar cal = Calendar.getInstance();
				java.util.Date date = cal.getTime();
				String myTime = sdFormat.format(date);
				String createTime = nyr.format(date);
				TblFlow flow = null;
				if (flowId != null && flowId.toString().trim().length() > 0) {
					flow = this.tblFlowMapper.findFlowInfoById(flowId.toString());
				}

				if ("HTGL005".equals(flow.getFlownumber()) || "HTGL002".equals(flow.getFlownumber()) || "HTGL007".equals(flow.getFlownumber())) {
					//TblContractTypeof type = this.tblContractTypeofMapper.findBytypeId(typeId);
					String no = "中船投[2022]" + DateUtils.dateToUnixTimestamp();
					dataMap.put("contractno", no);
				}
				dataMap.put("flowname", flow.getFlowname());
				dataMap.put("flowid", flowId);
				dataMap.put("createDate", createTime);
				resultMap.put("code", "1");
				resultMap.put("msg", "访问接口成功");
				resultMap.put("data", dataMap);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return resultMap;
		}
	}

    @Override
    public List<TblContractTypeof> findAllList(BigDecimal orgid, int parentId) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			return tblContractTypeofMapper.findAllList(orgid, parentId);
		} else {
			return tblContractTypeofMapper.findAllList(orgid, parentId);
		}
    }
}
